package count_down_dao

import (
	"go_server/game_server/database/mysql"
	"go_server/zinx/zlog"
	"go_server/zinx/zutils"
	"gorm.io/datatypes"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type CountDown struct {
	RoleId             int64                               `gorm:"column:role_id"`
	HeroSummonLastTime datatypes.JSONType[map[int32]int64] `gorm:"column:hero_summon_last_time"`
	HadWeedList        datatypes.JSONSlice[int32]          `gorm:"column:had_weed_list"`
	EventList          datatypes.JSONSlice[int32]          `gorm:"column:event_list"`
	CollectFoodList    datatypes.JSONSlice[int32]          `gorm:"column:collect_food_list"`
	GuideList          datatypes.JSONSlice[int32]          `gorm:"column:guide_list"`
	BuildStates        datatypes.JSONType[map[int32]int64] `gorm:"column:build_states"`
	BuildFightSceneIds datatypes.JSONSlice[int32]          `gorm:"column:build_fight_scene_ids"`
	MapBuildIds        datatypes.JSONSlice[int32]          `gorm:"column:map_build_ids"`
}

func (CountDown) TableName() string {
	return "count_down"
}

var (
	all_count_down_field = zutils.GetGormFields(CountDown{})
)

func GetCountDownByRoleId(RoleId int64, fields ...[]string) *CountDown {
	db := mysql.GetServerDBConnection()
	var countDown CountDown

	var selectFields []string

	if len(fields) > 0 {
		selectFields = fields[0]
	} else {
		selectFields = all_count_down_field
	}

	if err := db.Select(selectFields).Where("role_id=?", RoleId).First(&countDown).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetCountDownByRoleId ERR!!! fields: %v, RoleId: %s, err: %v", fields, RoleId, err)
		}
		return nil
	}
	return &countDown
}

func UpdateCountDown(countDown *CountDown, fields []string) {
	if countDown.HeroSummonLastTime.Data() == nil {
		heroSummonLastTime := make(map[int32]int64)
		countDown.HeroSummonLastTime = datatypes.NewJSONType(heroSummonLastTime)
	}

	if countDown.HadWeedList == nil {
		countDown.HadWeedList = make([]int32, 0)
	}

	if countDown.EventList == nil {
		countDown.EventList = make([]int32, 0)
	}

	if countDown.CollectFoodList == nil {
		countDown.CollectFoodList = make([]int32, 0)
	}

	if countDown.GuideList == nil {
		countDown.GuideList = make([]int32, 0)
	}

	if countDown.BuildStates.Data() == nil {
		buildStates := make(map[int32]int64)
		countDown.BuildStates = datatypes.NewJSONType(buildStates)
	}

	if countDown.BuildFightSceneIds == nil {
		countDown.BuildFightSceneIds = make([]int32, 0)
	}

	if countDown.MapBuildIds == nil {
		countDown.MapBuildIds = make([]int32, 0)
	}

	db := mysql.GetServerDBConnection()

	if err := db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "role_id"}},
		DoUpdates: clause.AssignmentColumns(fields),
	}).Create(countDown).Error; err != nil {
		zlog.Errorf("create or update count_down %v data failed: %v", countDown, err)
	}
}
